package com.wyix.create;

import java.util.Random;

/**
 * 多任务下载器
 *
 * @author wangdx
 * @since 2025/8/4
 */
public class FileDownloader implements Runnable {
    private String fileName;
    private int fileSize;

    public FileDownloader(String fileName, int fileSize) {
        this.fileName = fileName;
        this.fileSize = fileSize;
    }

    @Override
    public void run() {
        System.out.println("开始下载: " + fileName);
        Random random = new Random();
        int downloaded = 0;

        while (downloaded < fileSize) {
            // 模拟下载速度波动
            int speed = random.nextInt(10) + 1;
            downloaded += speed;
            if (downloaded > fileSize) downloaded = fileSize;

            System.out.printf("%s: 已下载 %d%% [%d/%d MB]\n",
                    fileName, (downloaded * 100) / fileSize, downloaded, fileSize);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                System.out.println(fileName + " 下载被取消!");
                return;
            }
        }
        System.out.println("✅ " + fileName + " 下载完成!");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new FileDownloader("电影.mp4", 50));
        Thread t2 = new Thread(new FileDownloader("音乐.mp3", 15));
        Thread t3 = new Thread(new FileDownloader("游戏.zip", 100));

        t1.start();
        t2.start();
        t3.start();
    }
}
